var mgeUser = {
    tableid: "table1",
    layerindex: null,
    bsTable: null,
    idselect: null
};
mgeUser.openDlg = function (title) {
    var hei = $(window).height() - 20;
    var wi = $(window).width() - 20;
    layer.open({
        type: "1",
        title: title ? title : "添加",
        area: [(wi > 650 ? 650 : wi) + 'px', (hei > 500 ? 500 : hei) + 'px'],
        shade: 0.4,
        maxmin: true,
        btn: ["确定", "取消"],
        content: $("#useropt"),
        scrollbar: false,
        yes: function (index) {
            $("#form_opt").submit();
            //mgeUser.postAjaxFrom();
            mgeUser.layerindex = index;
        }, btn2: function (index) {
            mgeUser.clearInputs();
        }, cancel: function () {
            mgeUser.clearInputs();
        }
    });
};
mgeUser.clearInputs = function () {
    var ipts = $("#form_opt").find("input");
    ipts.each(function (i, v) {
        $(v).val("");
        var er = $(v).next();
        if (er != null) {
            er.remove();
        }
        var hs = $(v).parents(".col-md-8");
        hs.removeClass("has-success");
        hs.removeClass("has-error");
    });
}
mgeUser.initColumn = function () {
    return [[{
        field: 'selectItem', radio: true
    }, {
        title: '用户id',
        field: 'userId',
        width: "100px",
        align: 'center',
        valign: 'middle',
        formatter: function (v, row) {
            return cmm.strLen(v, 8);
        }
    }, {
        title: '用户名', field: 'username', width: "200px", align: 'center', valign: 'middle', formatter: function (v) {
            return v;
        }
    }, {
        title: '盐', field: 'salt', width: "150px", align: 'center', valign: 'middle', formatter: function (v, row) {
            return cmm.strLen(v, 8);
        }
    }, {
        title: '邮箱', field: 'email', width: "170px", align: 'center', valign: 'middle', formatter: function (v, r, i) {
            return v;
        }
    }, {
        title: '电话', field: 'mobile', width: "120px", align: 'center', valign: 'middle', formatter: function (v, r, i) {
            return v;
        }
    }, {
        title: '状态', field: 'status', width: "100px", align: 'center', valign: 'middle', formatter: function (v, row) {
            if (v == '1') {
                return "启动";
            } else if (v == "2") {
                return "锁定";
            } else if (v == "0") {
                return "未启动";
            } else if (v == '3') {
                return "注销";
            }
        }
    }, {
        title: '创建时间',
        field: 'createTime',
        width: "150px",
        align: 'center',
        valign: 'middle',
        formatter: function (v, row) {
            return v;
        }
    }]];
}
mgeUser.queryParams = function () {
    return cmm.serializeObject($("#form_search"));
}
mgeUser.resHeigth = function () {
    var he = $(window).height() - ($("#divsearch").height() + 20);
    return he;
}
mgeUser.addOnClick = function () {
    $("#add").on("click", function (e) {
        e.preventDefault();
        $("#userId").val("");
        $("#status").val("1");
        $("#status").trigger("chosen:updated");
        $("#password").rules("add", {required: true});
        $("#password2").rules("add", {required: true});
        $("#username").removeAttr("disabled");
        $("#password").removeAttr("disabled");
        $("#password2").removeAttr("disabled");
        mgeUser.openDlg();
    });
}
mgeUser.updateOnClick = function () {
    $("#update").on('click', function (e) {
        e.preventDefault();
        var row = mgeUser.bsTable.getSelections();
        if (row == null && row.length == 0) {
            layer.alert("请选中您要修改数据！");
        }
        mgeUser.openDlg("修改");
        $("#password").rules("add", {required: false});
        $("#password2").rules("add", {required: false});
        mgeUser.getByUserid(row[0].userId);

    });
}
mgeUser.getByUserid = function (id) {
    var lay = layer.load({shade: [0.1]});
    $.ajax({
        url: ctx + "/mge/adx/getUserid",
        data: {userid: id},
        dataType: "json",
        type: 'post',
        success: function (d, s) {
            layer.close(lay);
            if (d.code == '200') {
                cmm.fromData(d.data);
                $("#password").val("");
                var roleids = d.data.roleids;
                if (cmm.isNotNull(roleids)) {
                    var sids = roleids.split(",");
                    $("#roleids").select2("val", sids);
                }
                $("#username").attr("disabled", "disabled");
                $("#status").val(d.data.status);
                $("#status").trigger("chosen:updated");
                $("#form_opt").valid();
            } else {
                layer.alert(d.message);
            }
        }, error: function (sta) {
            layer.close(lay);
            layer.alert("请求失败，请重试或检查网络！");
        }
    });
}
mgeUser.delOnClick = function () {
    $("#del").on('click', function (e) {
        e.preventDefault();
        var row = mgeUser.bsTable.getSelections();
        if (row == null && row.length == 0) {
            layer.alert("请选中您要修改数据！");
        }
        var lay = layer.load({shade: [0.1]});
        $.ajax({
            url: ctx + "/mge/adx/delUser",
            data: {userid: row[0].userId},
            type: "post",
            dataType: "json",
            success: function (data, sta) {
                layer.close(lay);
                if (data != null && data.code == '200') {
                    cmm.layerMessge("删除成功");
                    mgeUser.refresh();
                }
            },
            error: function (sta) {
                layer.close(lay);
                layer.alert("请求失败，请重试或检查网络！");
            }
        })
    });
}
mgeUser.select = function () {
    var s = $(".bs-select").chosen({width: '100%', disable_search: true});
    //show.bs.select
    //shown.bs.select 当下拉菜单对用户可见出发
    //loaded.bs.select 初始化后触发
    //hide.bs.select
    $(".bs-select").on("change", function (e, params) {

    });
    return s;
}
mgeUser.postAjaxFrom = function () {
    $("#form_opt").validate({
        rules: {
            username: {
                "required": true, minlength: 3, maxlength: 20, textEnvail: true, remote: {
                    type: 'post',
                    url: ctx + "/mge/adx/ckUsername",
                    data: {
                        username: function () {
                            return $("#username").val();
                        }
                    },
                    dataType: 'html',
                    dataFilter: function (dd, type) {
                        var data = JSON.parse(dd);
                        if (data.code == 200 && data.data == true) {
                            return true;
                        } else {
                            return false;
                        }
                    }
                }
            },
            name: {"required": true, maxlength: 20, textChvail: true},
            password: {"required": true, maxlength: 8, minlength: 4},
            password2: {"required": true, maxlength: 8, minlength: 4, equalTo: "#password"},
            email: {"required": true, email: true},
            mobile: {"required": true, mobile: true}
        }, messages: {
            username: {"required": "请输入用户名", minlength: "最小3字符", maxlength: "最大20字符", remote: "用户名不可用"},
            name: {"required": "请输入姓名", maxlength: "最大20字符"},
            password: {"required": "请输入密码", maxlength: "最大8字符", minlength: "最小4字符", equalTo: "二次密码不一致"},
            password2: {"required": "请输入确认密码", maxlength: "最大8字符", minlength: "", equalTo: "二次密码不一致"},
            email: {"required": "请输入邮箱"},
            mobile: {"required": "请输入电话"}
        }, success: function (label) {

        }, onkeyup: function (element) {
            $(element).valid();
        }, onfocusout: false, errorElement: "em", errorPlacement: function (error, element) {
            $(error).css({"color": "red", "font-size": "15px"});
            $(element).parent().append(error);
        }, highlight: function (element, errorClass, validClass) {
            $(element).parents(".col-md-8").addClass("has-error").removeClass("has-success");
        }, unhighlight: function (element, errorClass, validClass) {
            $(element).parents(".col-md-8").addClass("has-success").removeClass("has-error");
        }, submitHandler: function () {
            if (!$("#form_opt").valid()) {
                return false;
            }
            mgeUser.ajax();
            return false;
        }
    });
}
mgeUser.refresh = function (pageNumber) {
    mgeUser.bsTable.refresh(mgeUser.queryParams(), pageNumber);
}
mgeUser.load = function () {
    mgeUser.bsTable.load(mgeUser.queryParams());
}
mgeUser.ajax = function () {
    debugger;
    var roleids = $("#roleids").select2("val");
    var param = cmm.serializeFormObject($("#form_opt"));
    if (roleids.length > 0) {
        param.roleids = roleids.join(",");
    }
    var lay = layer.load(0, {shade: [0.1]});
    var statue = mgeUser.idselect.val();
    param.status = statue;
    if ($("#userId").val() == "") {
        $.ajax({
            url: ctx + "/mge/adx/addUserRole",
            data: param,
            type: "post",
            dataType: "json",
            timeout: 30000,
            success: function (data, stat, jqh) {
                layer.close(lay);
                layer.close(mgeUser.layerindex);
                mgeUser.clearInputs();
                if (data.code == '200') {
                    mgeUser.refresh(1);
                    cmm.layerMessge("添加成功！");
                } else {
                    layer.alert(data.message);
                }
            },
            error: function (d) {
                layer.close(lay);
                layer.alert("请求失败请重试或检查网络！");
            }
        });
    } else {
        $.ajax({
            url: ctx + "/mge/adx/updateUserRole",
            data: param,
            type: "post",
            dataType: "json",
            success: function (data, stat, jqh) {
                layer.close(lay);
                layer.close(mgeUser.layerindex);
                mgeUser.clearInputs();
                if (data.code == '200') {
                    mgeUser.refresh();
                    cmm.layerMessge("修改成功！");
                } else {
                    layer.alert(data.message);
                }
            },
            error: function (d) {
                layer.close(lay);
                layer.alert("请求失败请重试或检查网络！");
            }
        });
    }
}
var myLayout;
$(function () {
    myLayout = $('body').layout({
        north__minSize: 50,
        north__maxSize: 400,
        togglerContent_open: '<div class="ui-icon"></div>',
        togglerContent_closed: '<div class="ui-icon"></div>'
        // , spacing_open: 10
        // , spacing_closed: 10
    });
    $.ajax({
        url: ctx + '/mge/adx/listrole',
        data: {},
        type: 'post',
        dataType: 'json',
        success: function (data) {
            // var data = [];
            // var content = $("#name").val();
            // var arr = content.split(",");

            // instance = $select.data('select2');
            // if(instance) {
            //     $select.select2('destroy').empty();
            // }
            var arr = [];
            for (var r in data.rows) {
                var role = data.rows[r];
                arr.push({"id": role.roleId, "text": role.roleName});
            }
            $("#roleids").select2({
                language: "zh-CN",
                width: '100%',
                data: arr,
                containerCssClass: 'hh',
                dropdownCssClass: 'lly'
            });
            $("#roleids").on("select2:select", function () {
                $(this).valid();
            });
        }, error: function () {
            layer.alert("请求失败！");
        }
    });

    getData();
    $("#form_search").on("submit", function (e) {
        mgeUser.bsTable.destroy()
        getData();
        return false;
    });
    mgeUser.addOnClick();
    mgeUser.updateOnClick();
    mgeUser.delOnClick();
    mgeUser.idselect = mgeUser.select();
    mgeUser.postAjaxFrom();
});

function getData() {
    var bs = new BgdataTable();
    var opt = new BgOption(mgeUser.tableid, ctx + "/mge/adx/listUser?rad=" + new Date().getTime(), mgeUser.initColumn(), mgeUser.queryParams(), mgeUser.resHeigth());
    opt.toolbarId = "table1Toolbar";
    opt.onClickRow = function (row, el, field) {
        btnXs(row);
    }
    opt.onCheck = function (row) {
        btnXs(row);
    }

    function btnXs(row) {
        if (row.userId == "1") {
            $("#update").hide();
            $("#del").hide();
        } else {
            $("#update").show();
            $("#del").show();
        }
    }

    bs.draw(opt);
    mgeUser.bsTable = bs;
}